﻿/*
 *  调用C++接口说明 http://confluence.open.com.cn:8090/pages/viewpage.action?pageId=16712410
 */

var remainTime;// 考试剩余时间
var readyType = 1;// 当前动作  1：打开/关闭摄像头  2：抓拍照片
var timer;// 抓拍照片的定时器
var activeCapture = false;// 是否后端主动抓拍(管理端老师拍照)
var selfCapture = true;// 是否前端主动抓拍(考生进入答题页抓拍   考生提交试卷时抓拍)
var isSubmit = false;// 是否提交试卷
var websocket = null;
var postUrl = window.location.host;// 服务器域名

(function () {
    var app = angular.module('myApp.Controllers', []);

    app.controller('ExamPaper', ['$scope', '$modal', 'examService', 'utils', function ($scope, $modal, examService, utils) {
        var srv = examService.list;

        $scope.isEnd = false;
        $scope.$on('to-parent', function (event, data) {
            $scope.isCanSubmit = data;
        });
        $scope.$on('to-parent2', function (event, data) {
            $scope.isBegin = data;
        });

        var methods = {
            // 获取学生信息
            getExamineeInfo: function () {
                srv.getExamineeInfo().success(function (data) {
                    $scope.examineeName = data.examineeName;
                    $scope.seatNo = data.seatNo;
                    $scope.examCardNo = data.examCardNo;
                    $scope.typeName = data.typeName;
                    $scope.certificateNo = data.certificateNo;
                    $scope.isShowSeat = ($scope.seatNo != 0);
                    $scope.examRoomId = data.examRoomId;

                    $scope.appId = data.appId;
                    $scope.planId = data.planId;
                    $scope.subjectId = data.subjectId;
                    $scope.examineeId = data.examineeId;
                });
            },
            // 加载试卷、试题、倒计时
            listPaper: function () {
                srv.getPaper().success(function (data) {
                    $scope.doing = '';
                    // 试卷结构
                    $scope.paper = data.testpaper;
                    // 大题集合
                    $scope.sections = data.testpaper.sectionTemplateCollection;
                    // 考生之前的作答结果集合
                    var answerDetails = data.answerDetails;
                    // 遍历试题，匹配考生作答
                    angular.forEach($scope.sections, function (s, sIndex, sArray) {
                        // 试题乱序
                        var newArr = [];
                        newArr = s.itemTemplateCollection.sort(function() {
                            return Math.random() - 0.5;
                        });
                        s.itemTemplateCollection = newArr;

                        angular.forEach(s.itemTemplateCollection, function (item, itemIndex, itemArray) {
                            item.itemIndexNew = itemIndex + 1;// 试题乱序后试题展示的index

                            // 填充考生之前的作答
                            for (var i = 0; i < answerDetails.length; i++) {
                                if (item.identifier.toLowerCase() == answerDetails[i].examPaperItemId.toLowerCase()) {
                                    item.isMarked = answerDetails[i].isMarked;
                                    item.candidateResponses = answerDetails[i].answerResults ? answerDetails[i].answerResults : [];
                                    item.itemCompletionStatus = answerDetails[i].isCompletion;
                                    // 填充作答之后跳出该循环
                                    break;
                                }
                            }

                            // 填充考生之前的离线作答
                            /*var offlineAnswer = JSON.parse($scope.offlineGetQuestionAnswer(item.identifier.toLowerCase()));
                            if (offlineAnswer) {
                                item.isMarked = offlineAnswer.isMarked;
                                item.candidateResponses = offlineAnswer.answerResults ? offlineAnswer.answerResults : [];
                                item.itemCompletionStatus = offlineAnswer.isCompletion;
                                // 作答更新状态为失败
                                item.updateStatus = 0;
                                // 再次进入考试，保存之前的离线作答
                                $scope.saveQuestionAnswer(item);
                            }*/

                            // 替换图片路径：题干中存在图片的情况
                            item.originalValue = $scope.convertImgUrl(item.originalValue);

                            /* 考生作答部分，遍历所有试题，处理考生作答 */
                            // 提示：考生作答字段candidateResponses的格式为：['A','B']或者['文本1','文本2']
                            // 得到学生作答列表
                            var userAnswer = item.candidateResponses;
                            // 选择题作答处理
                            if (item.assessmentItemType < 4) {
                                // 遍历选项
                                angular.forEach(item.choices, function (choice, choiceIndex, choiceArray) {
                                    // 替换图片路径：选项中存在图片的情况
                                    choice.content = $scope.convertImgUrl(choice.content);
                                    // 判断是否选中，增加自定义isSelected属性
                                    choice.isSelected = userAnswer.indexOf(choice.identifier) >= 0;
                                });
                            }
                            // 填空题作答处理
                            else if (item.assessmentItemType == 4) {
                                item.itemBodyContent = $scope.convertImgUrl(item.itemBodyContent);

                                // 拆分题干中的文本框
                                item.itemBodys = item.itemBodyContent.split(/<textentryinteraction><\/textentryinteraction>/);
                                for (var i = 0; i < item.itemBodys.length - 1; i++) {
                                    // 填充考生作答
                                    item.candidateResponses[i] = userAnswer[i] ? userAnswer[i] : '';
                                }
                            }
                            // 组合类选择题作答处理（阅读理解，完形填空）
                            else if (item.assessmentItemType == 5 || item.assessmentItemType == 7) {
                                // 完形填空显示单独处理
                                if (item.assessmentItemType == 7) {
                                    // 可能存在的几种情况
                                    var pattern1 = /<clozeGap responseidentifier="RESPONSE_\d+" \/>/gi;
                                    var pattern2 = /<clozeGap responseidentifier="RESPONSE_\d+"><\/clozeGap>/gi;
                                    var pattern3 = /<clozeGap responseidentifier=""\/>/gi;
                                    var pattern4 = /<clozeGap responseidentifier=""><\/clozeGap>/gi;
                                    var pattern = pattern1.test(item.originalValue) ? pattern1 : (pattern2.test(item.originalValue) ? pattern2 : (pattern3.test(item.originalValue) ? pattern3 : pattern4));
                                    var arr = item.originalValue.split(pattern);

                                    var str = '';
                                    $(arr).each(function (i) {
                                        if (i != 0) {
                                            str += '<span class="text-underline">&nbsp;&nbsp;&nbsp;&nbsp;' + i + '&nbsp;&nbsp;&nbsp;&nbsp;</span>';
                                        }
                                        str += arr[i];
                                    });

                                    item.originalValue = str;
                                }

                                // 遍历子题
                                angular.forEach(item.subItems, function (subItem, subItemIndex, subItemArray) {
                                    // 替换图片路径：组合类选择题子题题干情况
                                    if (subItem.originalValue)
                                        subItem.originalValue = $scope.convertImgUrl(subItem.originalValue);

                                    // 遍历子题选项
                                    angular.forEach(subItem.choices, function (subItemChioce, subItemChioceIndex, subItemChioceArray) {
                                        // 替换图片路径：组合类选择题子题选项情况
                                        subItemChioce.content = $scope.convertImgUrl(subItemChioce.content);
                                        // 判断是否选中，增加自定义isSelected属性
                                        subItemChioce.isSelected = userAnswer[subItemIndex] == subItemChioce.identifier;
                                    });
                                });
                            }
                            // 问答题作答处理
                            else if (item.assessmentItemType == 6) {
                                // 填充考生作答
                                var canResponses = [];
                                canResponses.push(userAnswer[0] ? userAnswer[0] : '');
                                item.candidateResponses = canResponses;
                            }
                        });
                    });
                });
            },
            // 失去焦点处理
            onBlur: function (curItem) {
                if (curItem.assessmentItemType == 6 && $scope.timingSave)
                    window.clearInterval($scope.timingSave);

                if (curItem.isExample || !$scope.isBegin)
                    return;

                // 填空题和问答题 - 输入框失去焦点处理
                switch (curItem.assessmentItemType) {
                    case 4: // 填空题
                    case 6: // 问答题
                        curItem.itemCompletionStatus = 1;
                        angular.forEach(curItem.candidateResponses, function (option, optionIndex, optionArray) {
                            if (option) curItem.itemCompletionStatus = 3;
                        });
                        break;
                };

                $scope.saveQuestionAnswer(curItem);
                $scope.doing = $scope.curId;
            },
            /* 
             * 选项试题处理方法 - 点击选项时处理
             * item 当前试题对象
             * choice 当前选项对象
             * index 子试题索引
             */
            onClick: function (curItem, curChoice, curIndex) {
                if (curItem.isExample || !$scope.isBegin)
                    return;

                $scope.curId = curItem.identifier;

                var arrayResult = [];
                switch (curItem.assessmentItemType) {
                    case 1: // 单选题
                    case 3: // 判断题
                        // 当前选中项是否已选中
                        var hadSelected = curChoice.isSelected;

                        // 当前curItem下所有choice都置为未选中
                        angular.forEach(curItem.choices, function (choice, choiceIndex, choiceArray) {
                            choice.isSelected = false;
                        });
                        // 更新当前选项的选中标识
                        curChoice.isSelected = !hadSelected;
                        // 如果试题未作答则标记为作答
                        if (curItem.itemCompletionStatus != 3) curItem.itemCompletionStatus = 3;

                        // 如果此前是选中的则本次为取消选中，则将试题完整状态更新为未完成
                        if (hadSelected) curItem.itemCompletionStatus = 1;

                        // 设置答案
                        arrayResult = [];
                        // 如果此前未选中则本次肯定选中了，则更新作答结果区域
                        if (!hadSelected)
                            arrayResult.push(curChoice.identifier);

                        // 更新作答
                        curItem.candidateResponses = arrayResult;
                        break;
                    case 2: // 多选题
                        // 遍历当前curItem下所有choice，如果和当前点击一致，则设置为相反状态，其他不改变
                        var itemDone = false;
                        arrayResult = [];
                        angular.forEach(curItem.choices, function (choice, choiceIndex, choiceArray) {
                            if (choice.identifier == curChoice.identifier) {
                                choice.isSelected = !choice.isSelected;
                            }
                            if (choice.isSelected) {
                                itemDone = true;
                                arrayResult.push(choice.identifier);
                            }
                        });

                        // 如果itemDone为false表示该curItem未作答
                        curItem.itemCompletionStatus = itemDone ? 3 : 1;

                        // 更新作答
                        curItem.candidateResponses = arrayResult;
                        break;
                    case 5: // 阅读理解题
                    case 7: // 完型填空题
                        arrayResult = [];
                        var doneCount = 0;
                        // 遍历所有小题
                        angular.forEach(curItem.subItems, function (subItem, subItemIndex, subItemArray) {
                            // 初始化当前小题为未作答
                            var itemSelected = false;
                            // 当前选中项是否已经选中
                            var hadSelected = curChoice.isSelected;
                            // 遍历小题选项 
                            angular.forEach(subItem.choices, function (subItemChoice, subItemChoiceIndex, subItemChoiceArray) {
                                // 如果是当前作答的小题
                                if (curIndex == subItemIndex) {
                                    // 设置为未选中
                                    subItemChoice.isSelected = false;
                                    // 如果是当前作答的小题的选项
                                    if (subItemChoice.identifier == curChoice.identifier) {
                                        subItemChoice.isSelected = !hadSelected;
                                    }
                                }
                                // 如果当前小题作答了
                                if (subItemChoice.isSelected) {
                                    // 已作答小题数加1
                                    doneCount++;
                                    // 设置当前小题为已作答
                                    itemSelected = true;
                                    // 将选中项标识添加入作答结果数组    
                                    arrayResult.push(subItemChoice.identifier);
                                }
                            });
                            // 如果小题未作答则需要给作答结果数组添加默认空值
                            if (!itemSelected) {
                                arrayResult.push('');
                            }
                        });

                        // 如果所有小题都作答了，表示该curItem已作答
                        curItem.itemCompletionStatus = curItem.subItems.length == doneCount ? 3 : 1;

                        // 更新作答
                        curItem.candidateResponses = arrayResult;
                        break;
                    default:
                        break;
                }

                //if ($scope.doing != $scope.curId)
                //    $scope.saveQuestionAnswer(curItem);

                $scope.doing = $scope.curId;
            },
            /*
             * 当前焦点时的处理
             * 问答题默认每10秒保存
             * 其余情况1分钟保存
             * 这里也算一个小优化，在 blur 时有一次保存，这时新的 foucs 会关闭之前的定时器，重启一个新的定时保存器
             */
            onFocus: function (curItem) {
                if (curItem.assessmentItemType == 6) {
                    if ($scope.timingSave)
                        window.clearInterval($scope.timingSave);

                    // 定时保存答案（20s）
                    $scope.timingSave = window.setInterval(function () {
                        $scope.saveQuestionAnswer(curItem);
                    }, 20000);
                }
            },
            // 获取字符串的全部长度，包括空格等
            textLenght: function (id) {
                return document.getElementById('text_' + id).value.length;
            },
            // 替换图片路径
            convertImgUrl: function (value) {
                var imgPath = '/images/' + planId + '/' + examsiteid + '/papers/' + subjectcode + '/AssessmentItems/';
                var secObj = $('<section>' + value + '</section>');
                $(secObj).find('img').each(function (i, data) {
                    var imgObj = $(data);
                    //imgObj.removeAttr('height').attr('width', '100%');
                    var src = imgObj.attr('src');
                    if (src.indexOf('/images/') < 0 && src.indexOf('data:') < 0 )
                        imgObj.attr('src', imgPath + src);
                });
                return secObj.html();
            },
            // 是否可以全屏显示试题
            openView: function (item) {
                return (item.assessmentItemType == 5 || item.assessmentItemType == 7);
            },
            // 导航
            resultClass: function (item) {
                var result = '';
                if (item.itemCompletionStatus == 3)
                    result = 'done';
                if (item.identifier == $scope.curId)
                    result = 'doing';

                // updateStatus：0失败，1成功，2上传中
                if (item.updateStatus != undefined) {
                    switch (item.updateStatus) {
                        case 0:
                            result += ' failed';
                            break;
                        case 1:
                            result += '';
                            break;
                        case 2:
                            result += ' uploading';
                            break;
                    }
                }

                result += item.isMarked ? ' mark' : '';

                return result;
            },
            // 描述
            resultTitle: function (item) {
                var result = '';
                if (item.itemCompletionStatus == 3)
                    result = '已作答完毕';
                else if (item.identifier == $scope.curId)
                    result = '正在作答';
                if (item.isMarked)
                    result += '；已标记';
                // updateStatus：0失败，1成功，2上传中
                if (item.updateStatus != undefined) {
                    switch (item.updateStatus) {
                        case 0:
                            result += '；上传结果失败';
                            break;
                        case 1:
                            result += '；上传结果成功';
                            break;
                        case 2:
                            result += '；上传结果中';
                            break;
                    }
                }
                item.title = result;
            },
            // 标记文字样式
            markClass: function (item) {
                if (!$scope.isBegin)
                    return;

                var result = item.isMarked ? 'marked' : 'unmark';
                return result;
            },
            // 更新标记
            mark: function (item) {
                if (!$scope.isBegin)
                    return;

                item.isMarked = !item.isMarked;
                $scope.saveQuestionAnswer(item);
            },
            // 浮动层
            fullScreen: function (item) {
                var modal = utils.showItem({
                    msg: item,
                    ok: '关闭'
                });

                modal.result.then(function (item) {
                    // 如果是预览界面，不保存，直接返回
                    if ($scope.isPreview || !$scope.isBegin) return;

                    var fromModal = angular.copy(item);
                    // 遍历试题，匹配作答
                    angular.forEach($scope.sections, function (sdata, sindex, sarray) {
                        // 遍历section
                        angular.forEach(sdata.itemTemplateCollection, function (itemData, itemIndex, itemArray) {
                            // 遍历item
                            if (itemData.identifier == fromModal.identifier) {
                                itemData.subItems = fromModal.subItems;
                                itemData.candidateResponses = fromModal.candidateResponses;
                                itemData.itemCompletionStatus = fromModal.itemCompletionStatus;

                                // 保存一次作答结果
                                $scope.saveQuestionAnswer(item);
                                // 保存后直接返回，防止继续循环
                                return;
                            }
                        });
                    });
                });
            },
            // 提交试卷
            submit: function () {
                /*
                var offlineList = JSON.parse($scope.offlineGetAnswer());
                if(offlineList && offlineList.length>0){
                    utils.notify('本地存在未提交的试题作答，请先进行保存！', 'warning');
                    reutrn;
                }
                */

                // 提交前保存一次试卷
                $scope.saveAnswer($scope.paper, function (result) { /* ... */
                });

                $scope.isEnd = true;
                var totalItemCnt = 0;
                var notFinishCnt = 0;
                var uploadFailedCnt = 0;
                var markedCnt = 0;
                // 遍历试题，匹配作答
                angular.forEach($scope.sections, function (data, index, array) {
                    //遍历section
                    angular.forEach(data.itemTemplateCollection, function (data, index, array) {
                        //遍历item
                        if (data.itemCompletionStatus == 1 || data.itemCompletionStatus == 0) {
                            notFinishCnt++;
                        }
                        if (data.updateStatus == 0) {
                            uploadFailedCnt++;
                        }
                        if (data.isMarked == 1) {
                            markedCnt++;
                        }
                        totalItemCnt++;
                    });
                });
                var alertMsg = '确认要提交试卷么？';
                if (notFinishCnt > 0) {
                    alertMsg = '<p class="btn-message-font">您还有<span class="btn-message-font-color"> ' + notFinishCnt + ' </span>道题未作答，<span class="btn-message-font-color"> ' + uploadFailedCnt + ' </span>道题上传失败，<span class="btn-message-font-color"> ' + markedCnt + ' </span>道题标记。</p><p class="btn-message-font">是否确认提交？</p>';
                } else if (markedCnt > 0) {
                    alertMsg = '<p class="btn-message-font">您还有<span class="btn-message-font-color"> ' + markedCnt + ' </span>道题标记。</p><p class="btn-message-font">是否确认提交？</p>';
                }
                var model = utils.confirm({
                    msg: alertMsg,
                    ok: '确认提交',
                    cancel: '继续作答'
                });
                model.result.finally(function () {
                    $scope.isEnd = false;
                });
                model.result.then(function () {
                    if( loginMode == "3" || loginMode == "4" ){// 登录方式要求人脸识别
                        websocket.close();// 提交时关闭websocket
                        // 提交时抓拍一张照片
                        try {
                            isSubmit = true;
                            selfCapture = true;// 是否前端主动拍照
                            CSharpFunction.captureImage();
                        } catch (err) {}
                    }


                    // 提交试卷，开始注销倒计时
                    srv.submitPaper(1).success(function (data) {
                        if (data.resultType == 'Success') {
                            // message 为12表示必考模式下，已完成所有科目的考试
                            if (data.message == '12') {
                                window.location.href = 'CompletionPage';
                            }

                            var score = parseInt(data.appendData);

                            // 小于0，则为不显示成绩
                            var message = '';
                            if (score < 0) {
                                message = '试卷已顺利提交，祝您取得满意的成绩！';
                            } else {
                                message = '考试结束，您的考试成绩：' + score + '分。';
                            }

                            $modal.open({
                                templateUrl: '../../App/views/ExamPaper/countDown.html',
                                controller: 'countDownController',
                                backdrop: 'static',
                                keyboard: false,
                                resolve: {
                                    params: function () {
                                        return message;
                                    }
                                }
                            });
                        } else {
                            utils.notify(data.message, 'warning');
                        }
                    });
                });
            },
            // 再次发起保存单题作答结果动作，用于之前保存失败的再次发起保存的情况
            saveQuestionAnswerAgain: function (item) {
                if (item.updateStatus == 0)
                    $scope.saveQuestionAnswer(item);
            },
            // 保存单题作答结果
            saveQuestionAnswer: function (item) {
                // 如果是预览界面，不保存，直接返回
                if ($scope.isPreview || !$scope.isBegin) return;

                var answer = {
                    examPaperInfoId: $scope.paper.identifier,
                    examPaperItemId: item.identifier,
                    sequenceIndex: item.sequenceIndex,
                    isCompletion: item.itemCompletionStatus,
                    answerResults: item.candidateResponses ? item.candidateResponses : [],
                    isMarked: item.isMarked
                };

                /*
                 * 0 保存失败
                 * 1 保存成功
                 * 2 Session 丢失
                 * 3 已被强制交卷
                 * 4 已在其他考试机登录
                 * 5 已交卷
                 */
                // updateStatus：0失败，1成功，2上传中
                item.updateStatus = 2;
                try {
                    srv.saveQuestionAnswer(answer).success(function (data) {
                        $scope.operSaveAnswer(data, function (result) {
                            item.updateStatus = result.statusCode;
                        });
                        // 保存成功时删除离线作答
                        if (data.statusCode == 1) {
                            $scope.offlineRemoveAnswer(answer);
                        } else {
                            $scope.offlineSaveAnswer(answer);
                        }
                    }).error(function () {
                        item.updateStatus = 0;
                        $scope.offlineSaveAnswer(answer);
                    });
                } catch (e) {
                    item.updateStatus = 0;
                    $scope.offlineSaveAnswer(answer);
                }
            },
            // 新增离线作答
            offlineSaveAnswer: function (answer) {
                if (typeof CSharpFunction != 'undefined') {
                    return CSharpFunction.SaveAnswer($scope.appId, $scope.planId, $scope.subjectId, $scope.examineeId, answer.examPaperInfoId, answer.examPaperItemId, JSON.stringify(answer));
                }
                return false;
            },
            // 删除离线作答
            offlineRemoveAnswer: function (answer) {
                if (typeof CSharpFunction != 'undefined') {
                    return CSharpFunction.RemoveAnswer($scope.appId, $scope.planId, $scope.subjectId, $scope.examineeId, answer.examPaperInfoId, answer.examPaperItemId);
                }
                return false;
            },
            // 获取离线作答
            offlineGetAnswer: function () {
                if (typeof CSharpFunction != 'undefined') {
                    return CSharpFunction.GetAnswer($scope.appId, $scope.planId, $scope.subjectId, $scope.examineeId, $scope.paper.identifier);
                }
                return 'null';
            },
            // 获取试题离线作答
            offlineGetQuestionAnswer: function (qid) {
                if (typeof CSharpFunction != 'undefined') {
                    return CSharpFunction.GetQuestionAnswer($scope.appId, $scope.planId, $scope.subjectId, $scope.examineeId, $scope.paper.identifier, qid);
                }
                return 'null';
            },
            // 保存作答结果
            saveAnswer: function () {
                return;
                // 如果是预览界面，不保存，直接返回
                if ($scope.isPreview || !$scope.isBegin) return;

                var answerList = [];
                angular.forEach($scope.sections, function (s, sIndex, sArray) {
                    angular.forEach(s.itemTemplateCollection, function (item, itemIndex, itemArray) {
                        var answer = {
                            examPaperInfoId: $scope.paper.identifier,
                            examPaperItemId: item.identifier,
                            sequenceIndex: item.sequenceIndex,
                            isCompletion: item.itemCompletionStatus,
                            answerResults: item.candidateResponses ? item.candidateResponses : [],
                            isMarked: item.isMarked
                        };
                        answerList.push(answer);
                    });
                });

                /*
                 * 0 保存失败
                 * 1 保存成功
                 * 2 Session 丢失
                 * 3 已被强制交卷
                 * 4 已在其他考试机登录
                 * 5 已交卷
                 */
                srv.saveAnswer(answerList).success(function (data) {
                    $scope.operSaveAnswer(data);
                });
            },
            // 处理保存的结果
            operSaveAnswer: function (data, fn) {
                if (data.statusCode == 2) {
                    $modal.open({
                        templateUrl: '../../App/views/ExamPaper/countDown.html',
                        controller: 'countDownController',
                        backdrop: 'static',
                        keyboard: false,
                        resolve: {
                            params: function () {
                                return 'Session 丢失，请重新登录';
                            }
                        }
                    });
                } else if (data.statusCode == 3) {
                    // 提交试卷，开始注销倒计时
                    srv.submitPaper(4, true).success(function (data) {
                        if (data.resultType == 'Success') {
                            // message 为12表示必考模式下，已完成所有科目的考试
                            if (data.message == '12') {
                                window.location.href = 'CompletionPage';
                            }

                            var score = parseInt(data.AppendData);

                            // 小于0，则为不显示成绩
                            var message = '';
                            if (score < 0) {
                                message = '您的试卷已被强制提交！有问题请联系主考老师或系统管理员！';
                            } else {
                                message = '考试结束，您的考试成绩：' + score + '分。';
                            }

                            $modal.open({
                                templateUrl: '../../App/views/ExamPaper/countDown.html',
                                controller: 'countDownController',
                                backdrop: 'static',
                                keyboard: false,
                                resolve: {
                                    params: function () {
                                        return message;
                                    }
                                }
                            });
                        } else {
                            utils.notify(data.message, 'warning');
                        }
                    });
                } else if (data.statusCode == 4) {
                    $modal.open({
                        templateUrl: '../../App/views/ExamPaper/countDown.html',
                        controller: 'countDownController',
                        backdrop: 'static',
                        keyboard: false,
                        resolve: {
                            params: function () {
                                return '考生已在其他机器上登录，正在退出登录！';
                            }
                        }
                    });
                } else if (data.statusCode == 5) {
                    $modal.open({
                        templateUrl: '../../App/views/ExamPaper/countDown.html',
                        controller: 'countDownController',
                        backdrop: 'static',
                        keyboard: false,
                        resolve: {
                            params: function () {
                                return '已交卷，正在返回登录页';
                            }
                        }
                    });
                } else if (data.statusCode == 0) {
                    $scope.delayedRefreshTime(data.isDelayedAllExam, data.isDelayedExaminee);

                    // 显示保存失败？
                    if (fn) fn(data);
                } else if (data.statusCode == 1) {
                    $scope.delayedRefreshTime(data.isDelayedAllExam, data.isDelayedExaminee);
                    result = true;

                    // 显示保存成功？
                    if (fn) fn(data);
                }
            },
            // 延迟刷新时间
            delayedRefreshTime: function (isDelayedAllExam, isDelayedExaminee) {
                if (isDelayedAllExam) {
                    if (!$scope.isDelayedAllExam) {
                        $scope.isDelayedAllExam = true;

                        // 整场延时需要刷新倒计时
                        $scope.$broadcast('updateTime');

                        // 提示延时成功？
                    } else if (isDelayedExaminee) {
                        // 考生延时需要刷新倒计时
                        $scope.$broadcast('updateTime');

                        // 提示延时成功？
                    }
                } else if (isDelayedExaminee) {
                    // 考生延时需要刷新倒计时
                    $scope.$broadcast('updateTime');

                    // 提示延时成功？
                }
            },
            // 安全起见，禁用部分按键
            killKeys: function () {
                /*
                 // 屏蔽右键
                 document.oncontextmenu = new Function("window.event.returnValue=false;");
                 // 屏蔽选取
                 document.onselectstart = new Function("window.event.returnValue=false;");
                 // 屏蔽复制
                 document.oncopy = new Function("window.event.returnValue=false;");
                 // 屏蔽粘贴
                 document.onpaste = new Function("window.event.returnValue=false;");
                 // 屏蔽刷新，只能做到弹出提示框
                 //window.onbeforeunload = function () { return 'onbeforeunload'; }
                 */
                // 屏蔽按键
                $(document).keydown(function (e) {
                    // 屏蔽 Ctrl 组合键
                    //if (e.ctrlKey) {
                    //    // 非空格(32)、Shift(16)
                    //    if (e.keyCode != 32 && e.keyCode != 16) {
                    //        return $scope.shield(e);
                    //    }
                    //}
                    // 屏蔽 Shift 组合键
                    //if (e.shiftKey) {
                    //    // 非Ctrl(17)、非空格(32)
                    //    if (e.keyCode != 17 || e.keyCode != 32) {
                    //        return $scope.shield(e);
                    //    }
                    //}
                    // 屏蔽 Alt 组合键
                    if (e.altKey) {
                        return $scope.shield(e);
                    }
                    // 屏蔽 Win 键
                    if (e.keyCode == 91) {
                        return $scope.shield(e);
                    }
                    switch (e.keyCode) {
                        // Tab
                        case 9:
                        // Pause
                        case 19:
                        // Esc
                        case 27:
                        // F1-F12
                        case 112:
                        case 113:
                        case 114:
                        case 115:
                        case 116:
                        case 117:
                        case 118:
                        case 119:
                        case 120:
                        case 121:
                        case 122:
                        case 123:
                            return $scope.shield(e);
                    }
                });
            },
            shield: function (e) {
                e.keyCode = 0;
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        };
        angular.extend($scope, methods);

        $scope.getExamineeInfo();
        $scope.listPaper();
        $scope.killKeys();

        // 抓拍对比
        window.faceCompare = function (type, data) {
            if (data.indexOf('data:image/png;base64,') != -1) {
                data = data.substring(22);// 截取掉图片前面的  data:image/png;base64,
            }
            if (data.indexOf('data:image/jpeg;base64,') != -1) {
                data = data.substring(23);// 截取掉图片前面的  data:image/jpeg;base64,
            }
            var imgData = {token: Token, type: type, data: data};
            srv.SaveExamineePhoto(imgData).success(function (data) {
                if (data.resultType == "Success") {
                    // 抓拍人脸识别失败 并且不是提交试卷时抓拍  不是后端抓拍( && type != 0)  才给显示人脸识别结果
                    if (data.appendData == 0 && !isSubmit) {
                        clearTimeout(timer);// 清除抓拍定时器
                        $(".blog").show();
                        $("#promise").click(function () {
                            $(".blog").hide();
                            captureImage();// 点击承诺本人后开始抓拍
                        })
                    }
                } else {
                    console.log(data.message);
                }
            });
        };

        // 20 秒检查一次离线作答并保存到服务器
        /*window.setInterval(function () {
            angular.forEach($scope.sections, function (s, sIndex, sArray) {
                angular.forEach(s.itemTemplateCollection, function (item, itemIndex, itemArray) {
                    // 填充考生之前的离线作答
                    var offlineAnswer = JSON.parse($scope.offlineGetQuestionAnswer(item.identifier.toLowerCase()));
                    if (offlineAnswer) {
                        item.isMarked = offlineAnswer.isMarked;
                        item.candidateResponses = offlineAnswer.answerResults ? offlineAnswer.answerResults : [];
                        item.itemCompletionStatus = offlineAnswer.isCompletion;
                        // 作答更新状态为失败
                        item.updateStatus = 0;
                        // 再次进入考试，保存之前的离线作答
                        $scope.saveQuestionAnswer(item);
                    }
                });
            });
        }, 20000);*/
    }]);

    app.controller('DisplayTime', ['$scope', '$modal', '$timeout', 'examService', 'utils', function ($scope, $modal, $timeout, examService, utils) {
        var srv = examService.list;

        $scope.isDelayedAllExam = false;
        // 倒计时(1s)
        var oneSecond = window.setInterval(function () {
            if ($scope.isEnd)
                return;
            if ($scope.countdown >= -1) {
                $scope.$apply($scope.updateClock());
            }
        }, 1000);
        // 定时同步作答时间(10分)
        var syncTime = window.setInterval(function () {
            if ($scope.countdown > 5)
                $scope.$apply($scope.getTime());
        }, 1000 * 60 * 10);
        // 刷新时间显示
        $scope.$on('updateTime', function (event) {
            $scope.getTime();
        });

        var methods = {
            // 获取系统时间
            getTime: function () {
                srv.getTime().success(function (data) {
                    // 剩余时长（秒）
                    $scope.countdown = data.retainTime;
                    // 科目时长（秒）
                    $scope.examLength = data.examLength;
                    // 距离考试开始时间（秒）
                    $scope.timeToBegin = data.timeToBegin;
                    // 最小考试时长（分）
                    $scope.minExamTime = data.minExamTime;
                    // 是否已开始考试
                    $scope.isBegin = $scope.timeToBegin <= 0;
                });
            },
            // 计算显示时间
            updateClock: function () {
                // 已开始
                if ($scope.countdown > 0) { // 倒计时
                    $scope.mm = parseInt(parseInt($scope.countdown) / 60); // 计算剩余的分钟数
                    remainTime = $scope.mm;// 考试剩余时间(抓拍时计算定时器时间)
                    $scope.ss = parseInt(parseInt($scope.countdown) % 60); //计算剩余的秒数
                    // 剩余时间小于10分钟开始显示秒钟倒计时，否则只显示分钟倒计时

                    $scope.isShowSecond = false;
                    if ($scope.mm < 10) {
                        $scope.isShowSecond = true;
                        $scope.mm = '0' + $scope.mm;
                    }
                    if ($scope.ss < 10) {
                        $scope.ss = '0' + $scope.ss;
                    }

                    // 已用
                    $scope.ymm = parseInt((parseInt($scope.examLength) - parseInt($scope.countdown)) / 60); // 计算剩余的分钟数  
                    $scope.yss = parseInt((parseInt($scope.examLength) - parseInt($scope.countdown)) % 60); // 计算剩余的秒数
                    if ($scope.ymm < 10) {
                        $scope.ymm = '0' + $scope.ymm;
                    }
                    if ($scope.yss < 10) {
                        $scope.yss = '0' + $scope.yss;
                    }
                    $scope.countdown--;

                    // 大于指定的最早交卷时间则可以交卷，否则不许交卷
                    $scope.isCanSubmit = false;
                    if ((parseInt($scope.examLength) - parseInt($scope.countdown)) > (parseInt($scope.minExamTime) * 60)) {
                        $scope.isCanSubmit = true;
                        $scope.$emit('to-parent', $scope.isCanSubmit);
                        $scope.timeToSubmit = 0;
                    } else {
                        $scope.timeToSubmit = parseInt($scope.minExamTime) * 60 - (parseInt($scope.examLength) - parseInt($scope.countdown));
                    }
                    // 添加提交按钮显示
                    $scope.submitButtonText = $scope.isCanSubmit
                        ? '提交试卷'
                        : Math.floor($scope.timeToSubmit / 60) + '分' + Math.ceil($scope.timeToSubmit % 60) + '秒后可交卷';
                } else {
                    if (oneSecond)
                        window.clearInterval(oneSecond);

                    // 保存全部作答
                    $scope.saveAnswer($scope.paper, function () { /* ... */
                    });

                    // 提交试卷，开始注销倒计时
                    srv.submitPaper(3).success(function (data) {
                        if (data.resultType == 'Success') {
                            // message 为12表示必考模式下，已完成所有科目的考试
                            if (data.message == '12') {
                                window.location.href = 'CompletionPage';
                            }
                            var score = parseInt(data.appendData);
                            // 小于0，则为不显示成绩
                            var message = '';
                            if (score < 0) {
                                message = '试卷已自动提交，祝您取得满意的成绩！';
                            } else {
                                message = '考试结束，您的考试成绩：' + score + '分。';
                            }

                            $modal.open({
                                templateUrl: '../../App/views/ExamPaper/countDown.html',
                                controller: 'countDownController',
                                backdrop: 'static',
                                keyboard: false,
                                resolve: {
                                    params: function () {
                                        return message;
                                    }
                                }
                            });
                        } else {
                            utils.notify(data.message, 'warning');
                        }
                    });
                }

                $scope.isBegin = $scope.timeToBegin <= 0;

                $scope.$emit('to-parent2', $scope.isBegin);
            }
        };
        angular.extend($scope, methods);

        $scope.getTime();
    }]);

    app.controller('RespondenceTime', ['$scope', '$modal', '$timeout', 'examService', 'utils', function ($scope, $modal, $timeout, examService, utils) {
        var srv = examService.list;

        // 加载倒计时时间
        $scope.countDownTime = function () {
            srv.getTime().success(function (data) {
                $scope.timeToBegin = data.timeToBegin;

                // 倒计时(1s)
                var oneSecond = window.setInterval(function () {
                    $scope.$apply($scope.updateCountdown);
                }, 1000);
            });
        }

        $scope.updateCountdown = function () {
            // 倒计时
            if ($scope.timeToBegin > 1) {
                // 计算剩余的分钟数
                $scope.dmmN = parseInt(parseInt($scope.timeToBegin) / 60);
                // 格式化时间00：00
                if ($scope.dmmN < 10)
                    $scope.dmmN = '0' + $scope.dmmN;
                // 计算剩余的秒数
                $scope.dssN = parseInt(parseInt($scope.timeToBegin) % 60);
                if ($scope.dssN < 10)
                    $scope.dssN = '0' + $scope.dssN;
            }

            if ($scope.timeToBegin <= 1)
                window.location.href = 'ExamPaper?token=' + Token;

            $scope.timeToBegin--;
        };

        $scope.countDownTime();
    }]);

    app.controller('countDownController', ['$scope', '$modalInstance', 'examService', 'utils', 'params', '$filter', function ($scope, $modalInstance, examService, utils, params, $filter) {
        // 一般有以下几种情况
        // 您的试卷已被强制提交！有问题请联系主考老师或系统管理员！
        // 试卷已自动提交，祝您取得满意的成绩！
        // 考生已在其他机器上登录，正在退出登录！
        // 试卷已顺利提交，祝您取得满意的成绩！
        $scope.tipMessage = params;

        // 清除缓存
        commonFun.delCookie(commonFun.token);

        // 注销的时候的倒计时
        $scope.countDownTime = 10;

        var interval = window.setInterval(function () {
            $scope.$apply($scope.countDownTime = --$scope.countDownTime);

            if ($scope.countDownTime <= 0) {
                $modalInstance.close(true);
                window.clearInterval(interval);
                // LogOut();
                window.location.href = '/Examinee/Examlist?token=' + Token;
            }
        }, 1000);
    }]);


    /*=====================================websocket监听管理端发送的拍照请求===========================================*/

    if( loginMode == "3" || loginMode == "4" ){// 登录方式要求人脸识别
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + postUrl + "/socket/takePhoto");// 协议标识符是ws（如果加密，则为wss），服务器网址就是URL
        } else {
            alert('Not support websocket');
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            //console.log("websocket error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            //console.log("websocket open");
        };

        //连接关闭的回调方法
        websocket.onclose = function () {
            //console.log("websocket close");
        };

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            var data = JSON.parse(event.data);
            if (data.TakePhoto) {
                if (examineeId.toLowerCase() == (data.ExamCardNO).toLowerCase() && examSubjectId.toLowerCase() == (data.SubjectID).toLowerCase() ) {
                    activeCapture = true;// 是否后端主动抓拍
                    try {
                        CSharpFunction.captureImage();
                    } catch (err) {
                    }
                }
            }
        };

        //发送消息
        window.websocketSend = function (base64) {
            if (base64.indexOf('data:image/png;base64,') != -1) {
                base64 = base64.substring(22);// 截取掉图片前面的  data:image/png;base64,
            }
            if (base64.indexOf('data:image/jpeg;base64,') != -1) {
                base64 = base64.substring(23);// 截取掉图片前面的  data:image/jpeg;base64,
            }
            var params = JSON.stringify({
                type: "0",// 拍照类型: 管理端抓拍:0
                examPlanID: planId,// "计划ID"
                examSiteID: examsiteid, // "考点ID"
                examinerID: examineeId, // "考生ID
                examinerArrangeID: examineeArrangeId,// "考生编排ID"
                data: base64
            });
            websocket.send(params);
        };

        //监听窗口关闭事件
        window.onbeforeunload = function () {
            websocket.close();// 当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。

            try {
                CSharpFunction.closeCamera(); // 关闭摄像头   当窗口关闭时，释放摄像头,防止下次调用摄像头发现被占用抛异常问题
            } catch (e) {

            }
        };
    }

    /*=====================================websocket监听管理端发送的拍照请求===========================================*/

    if( loginMode == "3" || loginMode == "4" ){// 登录方式要求人脸识别
        isReady();// 开始调用C++抓拍
    }


})();

/*=============================抓拍照片 C++直接调用的方法  start========================*/

try {
    CSharpFunction.HideToolbar();// 隐藏客户端工具条
} catch (e) {

}

function isReady() {
    try {
        CSharpFunction.closeCamera(); // 关闭摄像头  先关闭,防止占用抛异常
        var isCameraReady = CSharpFunction.isCameraReady(); // 摄像头准备状态(或者台式机是否插入摄像头)
        if (isCameraReady) {
            CSharpFunction.startCamera(); // 启动摄像头
        } else {
            alert('请保证您的摄像头处于可用状态！');
        }
    } catch (err) {

    }
}

// 抓拍
function captureImage() {
    // 前端主动拍照(一进页面抓拍一次,提交试卷抓拍一次)
    if(selfCapture){
        setTimeout(CSharpFunction.captureImage,3000);// 3秒是为了等摄像头渲染完成,然后再抓拍
    }

    // 开始随机抓拍
    if (residueNumber > 0) {
        remainTime = $.trim(remainTime) == "" ? 1 : remainTime;// 如果暂时没有获取到倒计时,先默认给1
        var time = remainTime / residueNumber;//考试倒计时除以需要抓拍的数量
        time = rnd(1, time) * 1000 * 60;// 1000=1s 60000=1min
        timer = setTimeout(CSharpFunction.captureImage, time);// 触发抓拍(指定的毫秒数之后执行一次）
    }
}

// C++启动摄像头 或者 抓拍后 的回调方法
function notifyCameraReady(ready) {
    //alert("C++返回值===="+ ready);
    if (readyType == 1) {// readyType:1 启动/关闭摄像头  ready 1:启动摄像头、0:关闭摄像头
        if (ready == 1) {
            readyType = 2;
            captureImage();
        }
    } else if (readyType == 2) {// readyType:2  抓拍照片  ready 0:抓拍开始、1:抓拍完成
        if (ready == 1) {

        }
    }
}

//随机数
function rnd(n, m) {
    return parseInt(Math.random() * (m - n + 1) + n);
};

function showImage(base64) {
    //alert(base64);
    //show_image(base64, 276, 110, 'Captured Image');

    if (!activeCapture) {
        if(selfCapture){// 前端主动拍照(一进考试页拍照  提交试卷拍照)
            selfCapture = false;
            faceCompare(1, base64);// 考试抓拍:1  登录拍照:2
        }else{// 考试随机抓拍
            residueNumber--;// 只有随机抓拍限定抓拍数量
            faceCompare(1, base64);// 考试抓拍:1  登录拍照:2
            captureImage();
        }
    }else {// 管理端请求拍照
        activeCapture = false;
        // websocketSend(base64);
        faceCompare(0, base64);// 考试抓拍:1  登录拍照:2   后端拍照:0
    }
}

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

/*==================C++直接调用的方法  end========================*/